<template>
  <div class="flymeTag">
    <a-tag :key="tag" :closable="index >= 0" :afterClose="() => handleClose(tag)" v-for="(tag, index) in tags">{{tag}}</a-tag>
    <a-input v-if="inputVisible" ref="input" type="text" size="small" :style="{ width: '78px' }" :value="inputValue" @change="handleInputChange" @blur="handleInputConfirm" @keyup.enter="handleInputConfirm"/>
    <a-tag v-else @click="showInput" style="background: #fff; borderStyle: dashed;">
      <a-icon type="plus"/>
      添加标签
    </a-tag>
  </div>
</template>

<script>
  export default {
    name: 'fTag',
    model: {
      prop: 'value',
      event: 'change.value'
    },
    props: {
      value: {
        type: [String, Array],
        default: ''
      }
    },
    data() {
      return {
        tags: [],
        inputVisible: false,
        inputValue: ''
      }
    },
    watch: {
      value(value) {

        this.initValue(value)
      }
    },
    methods: {
      initValue(value) {
        if (value) {
          this.tags = value.split(',')
        }
      },
      handleClose(removedTag) {
        const tags = this.tags.filter(tag => tag !== removedTag)
        this.tags = tags
        this.$emit('change', tags.join(','))
      },
      handleInputChange(e) {
        this.inputValue = e.target.value
      },
      handleInputConfirm() {
        const inputValue = this.inputValue
        let tags = this.tags
        if (inputValue && tags.indexOf(inputValue) === -1) {
          tags = [...tags, inputValue]
        }
        console.log(tags)
        Object.assign(this, {
          tags,
          inputVisible: false,
          inputValue: ''
        })
        this.$emit('change', tags.join(','))
      },
      showInput() {
        this.inputVisible = true
        this.$nextTick(function() {
          this.$refs.input.focus()
        })
      }
    },
    created() {
      console.log('tags', this.value)
      this.initValue(this.value)
    }
  }
</script>

